// 动态路由表处理程序

import { notEmpty } from '../utils/common'
import router from './index'
import { publicRoutes } from './public_routes'
import { privateRoutes } from './private_routes'
import Logger from '~/utils/logger'
import { useAuthorityStore } from '~/stores/authority'

/**
 * 初始化路由表，只加载公共路由，防止切换用户后路由表未更新
 */
export const initRoutes = () => {
  Logger.log('初始化路由表')
  // 先清空路由表
  const currRoutes = router.getRoutes()
  if (notEmpty(currRoutes)) {
    currRoutes.forEach(item => {
      router.removeRoute(item.name)
    })
  }
  // 再添加公共路由表
  if (notEmpty(publicRoutes)) {
    publicRoutes.forEach(item => {
      router.addRoute(item)
    })
  }
}

/**
 * 添加私有路由表
 * @param {*} permissions 用户的权限列表
 * @returns
 */
export const addPrivateRoutes = permissions => {
  Logger.log('添加私有路由表')
  // 先筛选出目录、菜单、页面权限
  const filtered = []
  permissions.forEach(item => {
    if (['directory', 'menu', 'view'].includes(item.type)) {
      filtered.push(item)
    }
  })
  // 再遍历添加有访问权限的路由
  privateRoutes.forEach(route => {
    filtered.forEach(menu => {
      if (route.name === menu.identifier && !router.hasRoute(route.name)) {
        router.addRoute(route)
      }
    })
  })
}

/**
 * 检查用户是否有权限访问该页面
 * @param {*} permissions 用户的权限列表
 * @param {*} routeName   要访问的页面名称
 * @returns
 */
export function canAccessRoute(routeName) {
  Logger.log('检查用户是否有权限访问该页面')
  const authorityStore = useAuthorityStore()
  if (!authorityStore.exist) {
    return false
  }
  let result = false
  authorityStore.authority.permissions.forEach(item => {
    if (['directory', 'menu', 'view'].includes(item.type) && routeName === item.identifier) {
      result = true
    }
  })
  return result
}
